import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:todo_app/components/FontIcon.dart';
import 'package:todo_app/components/Overlay/main.dart';
import 'package:todo_app/components/TextExt.dart';
import 'package:todo_app/components/TextInput/CustomTextInput.dart';
import 'package:todo_app/config/config.dart';
import 'package:todo_app/constants/DColor.dart';
import 'package:todo_app/controllers/CommonController.dart';
import 'package:todo_app/controllers/GroupController.dart';
import 'package:todo_app/controllers/TodoController.dart';
import 'package:todo_app/controllers/definitions/CreateTodoModelParams.dart';
import 'package:todo_app/controllers/definitions/GroupModel.dart';
import 'package:todo_app/controllers/definitions/ResultModel.dart';
import 'package:todo_app/layout/CustomCard.dart';
import 'package:todo_app/layout/Gaps.dart';
import 'package:todo_app/layout/Header.dart';
import 'package:todo_app/layout/ListItem.dart';
import 'package:todo_app/layout/Space.dart';
import 'package:todo_app/pages/todo/components/GroupPicker.dart';
import 'package:todo_app/utils/ApiService.dart';
import 'package:todo_app/utils/AppNavigator.dart';
import 'package:todo_app/utils/ExtHelper.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

Future showPublishTodo(BuildContext context, GroupModel group) {
  return Navigator.of(context).push(MaterialPageRoute(builder: (_)=> TodoPublishPage(group: group)));
}

class TodoPublishPage extends HookWidget {
  const TodoPublishPage({super.key, this.group});
  final GroupModel? group;

  @override
  Widget build(BuildContext context) {
    var titleController = useTextEditingController(text: "");
    var contentController = useTextEditingController(text: "");
    var imageList = useState<List<String>>([]);
    var loop = useState<bool>(false);
    var lunar = useState<bool>(false);
    var alertTime = useState<DateTime?>(null);
    var alertDuration = useState<OverlayBottomSheetAction<String>>(OverlayBottomSheetAction<String>(text: null));
    var selectedGroup = useState<GroupModel?>(group);
  
    useEffect(() {
      if(selectedGroup.value == null) {
        // 获取分组
        GroupController.currentGroupUsingGet().then((res)=> {
          selectedGroup.value = res.data
        });
      }
      return () {};
    }, []);

    /// 图片
    Widget createImageList (ValueNotifier<List<String>> imageList) {
      Widget addBtn () {
        return InkWell(
          onTap: () async {
            OverlayEntry? loading;
            try {
              List<String> selectImageList = [];
              final List<AssetEntity>? assetsList = await AssetPicker.pickAssets(
                context,
                pickerConfig: const AssetPickerConfig(),
              );
              if(assetsList == null) return;
              if (assetsList.length > 10 - imageList.value.length) {
                showOverlayToast("上传图片超出10个");
                return;
              }
              loading = showOverlayLoading(title: '正在上传');
              for (int i = 0; i < assetsList.length; i++) {
                var file = await assetsList[i].file;
                if (file == null) continue;
                var response = await ApiService.upload(CommonController.uploadFileUsingPostPath, 'file', file, {});
                var result = ResultModel()..fromJson(response.data);
                if (result.data != null) {
                  String? uploadFile = AppConfig.fileServer + (result.data as String);
                  selectImageList.add(uploadFile);
                } else {
                  break;
                }
              }
              List<String> newImageList = [];
              for (String file in imageList.value) {
                newImageList.add(file);
              }
              newImageList.addAll(selectImageList);
              imageList.value = newImageList;
            } catch (e) {
              print(e);
            } finally {
              if (loading != null) loading.remove();
            }
          },
          child: Container(
            decoration: BoxDecoration(
                border: Border.all(
                    color: Colors.black.withOpacity(0.6),
                    width: 0.5
                )
            ),
            child: Icon(Icons.add, size: 30.dp,color: Colors.black.withOpacity(0.6),),
          ),
        );
      }

      Widget image (String? image) {
        return Stack(
          children: [
            InkWell(
              onTap: () {
                AppNavigator.pushNamed('previewImage',extra: image);
              },
              child: Container(
                width: double.infinity,
                height: double.infinity,
                decoration: BoxDecoration(
                    image: DecorationImage(
                      image: CachedNetworkImageProvider(image!),
                      fit: BoxFit.cover,
                    )
                ),
              ),
            ),
            Positioned(
              right: 3,
              top: 3,
              child: InkWell(
                onTap: () {
                  List<String> currentImageList = [];
                  for (String newImage in imageList.value) {
                    currentImageList.add(newImage);
                  }
                  currentImageList.remove(image);
                  imageList.value = currentImageList;
                },
                child: Container(
                    padding: const EdgeInsets.all(4),
                    decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(100)
                    ),
                    child: Icon(Icons.close,size: 13.dp,)
                ),
              ),
            )
          ],
        );
      }

      return Padding(
        padding: EdgeInsets.symmetric(
          horizontal: 16.dp,
          vertical: 0
        ),
        child: Column(
          children: [
            Gaps.vGap16,
            GridView.builder(
              itemCount: imageList.value.length + 1,
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 4,
                  mainAxisSpacing: 10.dp,
                  crossAxisSpacing: 10.dp,
                  childAspectRatio: 1
              ),
              itemBuilder: (BuildContext context, int index) {
                return index >= 10
                    ? const SizedBox()
                    : index == imageList.value.length && imageList.value.length < 10
                    ? addBtn()
                    : image(imageList.value[index]);
              },
            ),
            Gaps.vGap16,
            Row(
              children: [
                const Spacer(),
                Text(
                  '${imageList.value.length}/10',
                  style: TextStyle(
                      color: Colors.grey,
                      fontSize: 14.dp
                  ),
                )
              ],
            ),
            Gaps.vGap16,
          ],
        ),
      );
    }


    return Scaffold(
      appBar: Header(
        title: "发布待办事项",
        actions: [
          GestureDetector(
            onTap: () async {
              if(selectedGroup.value == null) {
                showOverlayToast("请选择所属分组");
                return;
              }
              if(titleController.text.isEmpty) {
                showOverlayToast("请输入标题");
                return;
              }
              if(contentController.text.isEmpty) {
                showOverlayToast("请选择输入内容");
                return;
              }
              if(alertTime.value == null) {
                showOverlayToast("请选择提醒时间");
                return;
              }
              if(loop.value) {
                if(alertDuration.value.text == null) {
                  showOverlayToast("请选择循环间隔");
                  return;
                }
              }
              var loading = showOverlayLoading(title: "正在保存");
              var formData = <String, dynamic> {
                'title': titleController.text,
                'content': contentController.text,
                'group_id': selectedGroup.value?.id,
                'attachments': imageList.value.join(","),
                'alert': {
                  'alert_name': titleController.text,
                  'alert_time': alertTime.value.toString(),
                  'alert_duration': alertDuration.value.value,
                  'alert_type': loop.value ? 'LOOP' : 'GENERAL',
                  'lunar': lunar.value
                }
              };
              try {
                var result = await TodoController.createUsingPost(CreateTodoModelParams()..fromJson(formData));
                if(result.status == 'success') {
                  showOverlayToast("保存成功");
                  AppNavigator.pop();
                } else {
                  showOverlayToast(result.msg ?? "保存失败");
                }
              } catch (e) {
                print(e); 
              } finally {
                loading.remove();
              }
            },
            child: Space(
              children: [
                FontIcon(icon: FontIcons.share, color: Colors.white, size: 16.dp,),
                Text(
                  "保存", style: TextStyle(color: Colors.white, fontSize: 16.dp),
                ),
              ],
            ),
          )
        ],
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            CustomCard(
              margin: EdgeInsets.only(top: 12.dp),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  ListItem(
                    height: 44.dp,
                    title: const Text("所属分组"),
                    border: true,
                    onTap: () async {
                      var pickGroup = await showGroupPicker(context);
                      print(pickGroup);
                      if(pickGroup != null) {
                        selectedGroup.value = pickGroup;
                      }
                    },
                    content: Expanded(
                      flex: 1,
                      child: TextExt.desc(
                        selectedGroup.value?.id != null ? selectedGroup.value?.group_name ?? "" : '请选择所属分组',
                        textAlign: TextAlign.right,
                        lineHeight: 1,
                        style: TextStyle(
                          color: alertTime.value == null ? DColor.descText : DColor.body,
                          fontSize: 14.dp
                        )
                      ),
                    ),
                  ),
                  ListItem(
                    height: 44.dp,
                    title: const Text("标题"),
                    border: true,
                    content: Expanded(
                      flex: 8,
                      child: CustomTextInput(
                        placeholder: "请输入标题",
                        textAlign: TextAlign.right,
                        controller: titleController,
                      ),
                    ),
                  ),
                  ListItem(
                    height: 88.dp,
                    title: const Text("说明"),
                    content: Expanded(
                      flex: 8,
                      child: CustomTextInput(
                        placeholder: "请输入说明",
                        textAlign: TextAlign.right,
                        controller: contentController,
                        maxLines: 4,
                      ),
                    ),
                  ),
                ],
              )
            ),
            CustomCard(
              margin: EdgeInsets.only(top: 12.dp),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  ListItem(
                    title: const Text("上传图片"),
                    height: 44.dp,
                    border: true,
                    actions: [
                      GestureDetector(
                        onTap: () {},
                        child: const Text("清除全部", style: TextStyle(color: DColor.primary),),
                      )
                    ],
                  ),
                  createImageList(imageList)
                ],
              )
            ),
            CustomCard(
              margin: EdgeInsets.only(top: 12.dp),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  ListItem(
                    height: 44.dp,
                    title: const Text("提醒时间"),
                    border: true,
                    content: Expanded(
                      flex: 1,
                      child: TextExt.desc(
                        alertTime.value.toYMDHm('请选择提醒时间'),
                        textAlign: TextAlign.right,
                        lineHeight: 1,
                        style: TextStyle(
                          color: alertTime.value == null ? DColor.descText : DColor.body,
                          fontSize: 14.dp
                        )
                      ),
                    ),
                    nextIcon: true,
                    onTap: () async {
                      var date = await showDatePicker(
                        context: context, 
                        initialDate: DateTime.now(), 
                        firstDate: DateTime.now(), 
                        lastDate: DateTime.now().add(const Duration(days: 365*100)),
                        initialEntryMode: DatePickerEntryMode.calendarOnly
                      );
                      if(date != null && context.mounted) {
                        var time = await showTimePicker(
                          context: context, 
                          initialTime: const TimeOfDay(hour: 8, minute: 0)
                        );
                        if(time != null) {
                          alertTime.value = DateTime(date.year, date.month, date.day, time.hour, time.minute);
                        }
                      }
                    },
                  ),
                  ListItem(
                    height: 44.dp,
                    title: const Text("是否循环"),
                    border: true,
                    actions: [
                      Switch(
                        value: loop.value, 
                        onChanged: (value)=> loop.value = value
                      )
                    ],
                  ),
                  Offstage(
                    offstage: !loop.value,
                    child: ListItem(
                      height: 44.dp,
                      title: const Text("循环间隔"),
                      content: Expanded(
                        flex: 1,
                        child: TextExt.desc(
                          alertDuration.value.text?.isNotEmpty != true ? '请选择循环间隔' : alertDuration.value.text!,
                          textAlign: TextAlign.right,
                          lineHeight: 1,
                          style: TextStyle(
                            color: alertDuration.value.text?.isNotEmpty != true ? DColor.descText : DColor.body,
                            fontSize: 14.dp
                          )
                        ),
                      ),
                      nextIcon: true,
                      border: true,
                      onTap: () async {
                        var actions = <OverlayBottomSheetAction<String>>[
                          OverlayBottomSheetAction(text: "间隔一年", value: '1y'),
                          OverlayBottomSheetAction(text: "间隔一季", value: '3m'),
                          OverlayBottomSheetAction(text: "间隔一月", value: '1m'),
                          OverlayBottomSheetAction(text: "间隔一周", value: '1w'),
                          OverlayBottomSheetAction(text: "间隔一天", value: '1d')
                        ];
                        var option = await showOverlayBottomSheet<String>(
                          actions: actions
                        );
                        if(option != null) {
                          alertDuration.value = actions.firstWhere((element) => element.value == option);
                        }
                      },
                    ),
                  ),
                  ListItem(
                    height: 44.dp,
                    title: const Text("是否农历"),
                    border: lunar.value,
                    actions: [
                      Switch(
                        value: lunar.value, 
                        onChanged: (value)=> lunar.value = value
                      )
                    ],
                  ),
                  Offstage(
                    offstage: !lunar.value,
                    child: ListItem(
                      height: 44.dp,
                      title: const Text("农历日期"),
                      content: Expanded(
                        flex: 1,
                        child: TextExt.desc(
                          alertTime.value.toLunarYMD("-"),
                          textAlign: TextAlign.right,
                          lineHeight: 1,
                          style: TextStyle(
                            color: alertDuration.value.text?.isNotEmpty != true ? DColor.descText : DColor.body,
                            fontSize: 14.dp
                          )
                        ),
                      ),
                      nextIcon: false
                    ),
                  ),
                ],
              )
            ),
          ],
        ),
      ),
    );
  }
}